package apps.web.service;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.security.GrantedAuthority;
import org.springframework.security.GrantedAuthorityImpl;
import org.springframework.security.providers.encoding.PasswordEncoder;
import org.springframework.security.userdetails.UserDetails;
import org.springframework.security.userdetails.UserDetailsService;
import org.springframework.security.userdetails.UsernameNotFoundException;

import webframe.common.helper.FormatTransformHelper;
import webframe.common.helper.LogonLog;
import apps.web.model.EntUser;
import apps.web.model.User;
import apps.web.model.UserRightSpec;
import apps.web.model.UserRightType;

public class UserService extends MyBaseService implements UserDetailsService {
	private static Log log = LogFactory.getLog(UserService.class);
	private PasswordEncoder passwordEncoder;

	public PasswordEncoder getPasswordEncoder() {
		return passwordEncoder;
	}

	public void setPasswordEncoder(PasswordEncoder passwordEncoder) {
		this.passwordEncoder = passwordEncoder;
	}

	public User findUserById(Serializable id) {
		return getUserDao().get(id);
	}

	// /////////implemented interface
	public UserDetails loadUserByUsername(String userName)
			throws UsernameNotFoundException, DataAccessException {
		String username = FormatTransformHelper.transEncodingFormBrowser(
				userName, "utf-8");
		User user = findUserByUserName(username);
		if (user == null) {
			log.info("用户名或密码错误 username=\"" + username + "\"");
			RuntimeException ex = new UsernameNotFoundException("用户名或密码错误");
			throw ex;
		}
		List<UserRightSpec> rights = findUserRightSpecByUserid(user.getId());
		getUserDao().getHibernateTemplate().getSessionFactory()
				.getCurrentSession().evict(user);
		List<GrantedAuthority> gas = new ArrayList<GrantedAuthority>();
		for (UserRightSpec userRightSpec : rights) {
			gas.add(new GrantedAuthorityImpl(userRightSpec.getRightCode()));
		}
		if (user.getUsername().equals("admin")) {
			gas.add(new GrantedAuthorityImpl("ROLE_USER"));
		}
		user.setAuthorities(gas.toArray(new GrantedAuthority[] {}));
		return user;
	}

	public User findUserByUserName(String username) {
		return getUserDao().findSingleByHql("from User t where t.username=?", new Object[] { username });
	}

	// //////////ciquser
	public List<UserRightSpec> findUserRightSpecByUserid(Long id) {
		return getUserRightSpecDao()
				.findByHql("from UserRightSpec t where t.userid=? order by id", new Object[] { id });
	}

	public List<UserRightType> findAllRightType() {
		List<UserRightType> list = getUserRightTypeDao().findByHql(
				"from UserRightType t where t.code <> 'ROLE_ADMIN' order by t.id");
		return list;
	}

	public User findCIQUserById(Serializable id) {
		return getUserDao().get(id);
	}

	public User findUserByCIQUserName(String username) {
		return getUserDao().findSingleByHql("from User t where t.username=?", new Object[] { username });
	}

	public List<User> findCIQUserByUsername(String username) {
		return getUserDao().findByHql("from User t where t.username=?", new Object[] { username });
	}

	public User saveCIQUser(User newuser) {
		return getUserDao().save(newuser);
	}

	public void deleteCIQUser(Long id) {
		getUserDao().delete(id);
	}

	public User updateUser(User user) {
		return getUserDao().merge(user);
	}

	public User updateCIQUser(User user) {
		return updateUser(user);
	}

	public List<UserRightSpec> findUserRightByUserid(Long id) {
		return getUserRightSpecDao()
				.findByHql("from UserRightSpec t where t.userid=? order by id", new Object[] { id });
	}

	public void updateUserRight(Long userid, String[] authoritys) {
		List<UserRightSpec> olds = findUserRightByUserid(userid);
		for (UserRightSpec userRightSpec : olds) {
			getUserRightSpecDao().delete(userRightSpec.getId());
		}
		for (String code : authoritys) {
			UserRightSpec right = new UserRightSpec();
			right.setUserid(userid);
			right.setRightCode(code);
			getUserRightSpecDao().save(right);
		}
	}

	// ////////////////ent user
	public EntUser findEntUserById(Serializable id) {
		return getEntUserDao().get(id);
	}

	public EntUser findEntUserByUsername(String username) {
		return getEntUserDao().findSingleByHql("from EntUser t where t.username=?", new Object[] { username });
	}

	public List<EntUser> findEntUserListByUsername(String username) {
		return getEntUserDao().findByHql("from EntUser t where t.username=?", new Object[] { username });
	}

	public EntUser saveEntUser(EntUser newuser) {
		return getEntUserDao().save(newuser);
	}

	public void deleteEntUser(Long id) {
		getEntUserDao().delete(id);
	}

	public EntUser updateEntUser(EntUser user) {
		return getEntUserDao().merge(user);
	}

	// ///////////////
	public void saveLogonLog(LogonLog log) {
		getLogonLogDao().save(log);
	}

}
